package com.wu.Backstage.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.wu.Backstage.check.MiddlelayerCheck;
import com.wu.Backstage.tool.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author wujian
 * @version 1.0
 * @date 2021/12/13 0013 23:08
 */

@Controller
@RequestMapping(value = "file")
public class FileController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MiddlelayerCheck oftenCheckf;

    @Autowired
    private HttpServletResponse response;

    private Tool result;

    @RequestMapping(value = "/upload", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @CrossOrigin
    public void upload(MultipartFile file,String msg){

        System.out.println(msg);
        String filename = file.getOriginalFilename();
        filename = IdUtil.fastSimpleUUID()+"_" + filename;
        String rootFilePath = System.getProperty("user.dir")+"\\src\\main\\resources\\files\\images\\"+filename;
        try {
            FileUtil.writeBytes(file.getBytes(),rootFilePath);
            String url = "http://localhost:8070/images/"+filename;
            result = oftenCheckf.isUserAccount(url,"上传成功!");
        } catch (IOException e) {
            e.printStackTrace();
            result = oftenCheckf.isUserAccount(null,"导入失败!");
        }
        oftenCheckf.Tres(result);
    }

    @RequestMapping(value = "/delFile", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @CrossOrigin
    public void delFile(String url) {

        String pathurl =  url.replace("http://localhost:8070/", "");
        String rootFilePath = System.getProperty("user.dir")+"\\src\\main\\resources\\files\\images\\"+pathurl;
        Boolean isTr = FileUtil.del(new File(rootFilePath));
        if(isTr){
            result = oftenCheckf.isUserAccount(1,"删除成功!");
        }else{
            result = oftenCheckf.isUserAccount(null,"清除失败!");
        }
        oftenCheckf.Tres(result);
    }





}